<template>
  <a-modal
    @ok="handleOk"
    @cancel="handleCancel"
    :open="props.isOpen"
    :title="props.editData.id ? '修改用户' : '新增用户'"
  >
    <a-form ref="formRef" :model="passData" :rules="rules">
      <a-form-item name="username" label="用户名">
        <a-input v-model:value="passData.username" />
      </a-form-item>
      <a-form-item name="email" label="邮箱">
        <a-input v-model:value="passData.email" />
      </a-form-item>
      <a-form-item :validateFirst="true" name="number" label="数量">
        <a-input-number v-model:value="passData.number" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import {
  defineProps,
  defineEmits,
  ref,
  watch,
  watchEffect,
  computed,
} from "vue";
import { message } from "ant-design-vue";
import { editUser, createUser } from "../../../../services/user-new";
// 包含新增、编辑功能的模态框
// 需要传入的props有（父传子）：
// 1. 是否打开模态框
// 2. 传入当前form需要编辑的数据
// 3. 到底是新增，还是修改

// 需要emit出去的事件有（子传父）：
// 1. 新增或者修改成功后，通知父组件：
// 2. 模态框是否关闭
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  editData: {
    type: Object,
    required: true,
    // default: {},
  },
  //   isCreate: {
  //     type: Boolean,
  //     required: true,
  //   },
});
const formRef = ref()
const rules = {
  username: [{ required: true, message: "请填写用户名" }],
  email: [{ required: true, message: "请填写邮箱" }],
  number: [
    { required: true, message: "请填写数量" },
  {validator(rule,value,callback){
    const isInteger = Number.isInteger(value)
    if (!isInteger || value<0) {
      callback('请输入正整数')
    }
    callback()
    console.log(rule,value,callback)
  }}
]
};
const passData = ref({ ...props.editData });
const emit = defineEmits(["onSuccess", "changeIsOpen"]);
const handleOk = async () => {
  await formRef.value.validateFields()
  if (props.editData.id) {
    // 修改
    await editUser(passData.value);
    message.success("新增成功");
    emit("onSuccess", "edit");
  } else {
    // 新增
    await createUser(passData.value);
    message.success("新增成功");
    emit("onSuccess", "create");
  }
};
const handleCancel = () => {
  emit("changeIsOpen");
};

// watch(
//   () => props.editData,
//   (value, oldValue) => {
//     passData.value = { ...value };
//     console.log(value, oldValue);
//   }
// );
// watchEffect(() => {
//   passData.value = { ...props.editData };
//   //   console.log(props.editData);
// });
// const isCreate = computed(() => !props.editData.id)
// const nowTitle = computed(() => {
//   return isCreate ? "新增用户-独立" : "修改用户-独立";
// });
</script>
<style></style>
